import type { ConsultOrderItem, FollowType } from '@/types/consult'
import { cancelOrder, deleteOrder, followTarget, getPrescriptionPic } from '@/services/consult'
import { ref } from 'vue'
import { ImagePreview, Toast, type FormInstance } from 'vant'
import { OrderType } from '@/enums'
import type { OrderDetail } from '@/types/order'
import { onMounted } from 'vue'
import { getMedicalOrderDetail } from '@/services/order'
import type { Ref } from 'vue'
import { sendMobileCode } from '@/services/user'
import { onUnmounted } from 'vue'
import type { CodeType } from '@/types/user'

// 逻辑复用

export const useFollow = (type: FollowType = 'doc') => {
  // 关注逻辑
  const loading = ref(false) // 加载中的状态，默认不开启
  // 点击按钮时的操作
  // 对象类型多的可以传递给少的，叫： 类型兼容
  const follow = async (item: { id: string; likeFlag: 0 | 1 }) => {
    // 发请求前开启loading , 在加载中
    loading.value = true
    try {
      await followTarget(item.id, type)
      // 请求成功后，修改好状态
      item.likeFlag = item.likeFlag === 1 ? 0 : 1
    } finally {
      // 不管成功和失败，都走
      loading.value = false
    }
  }

  // 导出
  return { loading, follow }
}

// 类型兼容
// const fn = (item: { id: number; name: string }) => {
//   console.log('类型兼容')
// }
// const obj = {
//   id: 10,
//   name: 'jack',
//   age: 18
// }

// fn(obj)

// 封装查看处方逻辑
export const useShowPrescription = () => {
  const showPrescription = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionPic(id)
      ImagePreview([res.data.url])
    }
  }
  return { showPrescription }
}

// 取消订单的操作
export const useCancelOrder = () => {
  const loading = ref(false)
  const onCancelOrder = async (item: ConsultOrderItem) => {
    try {
      loading.value = true
      await cancelOrder(item.id)
      // 修改订单的状态
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
      Toast.success('取消成功')
    } catch (error) {
      Toast.fail('取消失败')
    } finally {
      loading.value = false
    }
  }
  return { loading, onCancelOrder }
}

// 删除订单
// 删除成功的做的事不确定，可以通过出入函数来实现
// 传进来一个 函数 , 就会调用这个函数 ，哪里传来的哪里用
export const useDeleteOrder = (cb: () => void) => {
  const loading = ref(false)
  const deleteConsultOrder = async (item: ConsultOrderItem) => {
    try {
      loading.value = true
      await deleteOrder(item.id)
      // 删除成功 把list的item删掉 删除这条信息
      // emit('on-delete', item.id)
      // 详情里面删除就是跳转页面
      Toast.success('删除成功')
      cb && cb() // 如果传了cb这个函数，就调用cb函数!!
    } catch (error) {
      Toast.fail('删除失败')
    } finally {
      loading.value = false
    }
  }
  return { loading, deleteConsultOrder }
}

// 根据订单id获取订单的详情信息
export const useOrderDetail = (id: string) => {
  const order = ref<OrderDetail>() // 订单的详情信息
  const loading = ref(false)
  onMounted(async () => {
    loading.value = true
    try {
      const res = await getMedicalOrderDetail(id)
      order.value = res.data
    } finally {
      loading.value = false
    }
  })
  return { loading, order }
}

// 发送验证码
export const useMobileCode = (mobile: Ref<string>, type: CodeType) => {
  const time = ref(0)
  const form = ref<FormInstance | null>(null)
  let timerId: number
  const send = async () => {
    // 已经倒计时time的值大于0，此时不能发送验证码
    if (time.value > 0) return

    //校验输入框 validate验证表单 传入anme来验证表单项  通过ref可以获取到Form实例并调用实例方法
    // 验证不通过报错，阻止程序继续执行
    await form.value?.validate('mobile') //校验mobile字段  返回值是promise
    // 上面的校验成功发验证码
    // console.log('ok')
    await sendMobileCode(mobile.value, type)

    time.value = 60
    Toast.success('发送成功')

    // 开启倒计时
    if (timerId) clearInterval(timerId) //如果倒计时存在，清除倒计时，防止开启两次
    timerId = window.setInterval(() => {
      time.value--
      if (time.value <= 0) clearInterval(timerId)
    }, 1000)
  }
  //
  // 组件销毁
  onUnmounted(() => {
    window.clearInterval(timerId)
  })

  return { form, time, send }
}
